import math

from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render
from users.models import PersonModel

# Create users views here.


def add_person(request):
    """ 一次性添加95个人 """

    for i in range(1, 96):
        PersonModel.objects.create(name=f'wang {i} xin', age=10+i)

    return HttpResponse('add success!')


def paginate1(request, page=1):
    """
    手动分页功能
    数据 = [1, 2, 3, ... , 100]
    假设每页10个数据， per_page=10
    第几页                数据范围            数据下标范围         切片
    page=1               1 ~ 10             0 ~ 9              [0: 10]
    page=2               11 ~ 20            10 ~ 19            [10: 20]
    page=3               21 ~ 30            20 ~ 29             [20: 30]
    page=4               31 ~ 40            30 ~ 39             [30: 40]
    ...
    page=n                                                  [(n-1)*10: n*10]
    page=page                                         [(page-1)*per_page: page*per_page]
    """
    # 实现分页
    per_page = 10
    all_person = PersonModel.objects.all()  # 获取所有数据
    persons = all_person[(page-1)*per_page: page*per_page]  # 计算指定页是哪些数据

    total = PersonModel.objects.count()
    total_page = math.ceil(total / per_page)  # 向上取整得到总页数

    context = {
        'persons': persons,
        'total_page': range(1, total_page+1),
    }
    return render(request, 'paginate1.html', context=context)


def paginate2(request, page=1):
    """ django自带的分页器Paginator """
    per_page = 10
    all_person = PersonModel.objects.all()
    # Paginator的第一个参数是要分页的所有数据，第二个参数是每页多少个数据
    paginator = Paginator(all_person, per_page)
    # 获取第page页的数据
    persons = paginator.page(page)
    # 获取页码范围
    pages = paginator.page_range  # 是一个属性，可以直接遍历

    context = {
        'persons': persons,
        'pages': pages
    }
    return render(request, 'paginate2.html', context=context)
